package org.example.managere.repository.feibiao;

import org.example.managere.entity.feibiao.AmArchivesDegradation;
import org.example.managere.dto.feibiao.AmArchivesDegradationDto;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Repository
public interface AmArchivesDegradationRepository extends JpaRepository<AmArchivesDegradation, Integer> {
    
    /**
     * 根据电机ID查询退化记录
     */
    List<AmArchivesDegradation> findByMotorId_MotorId(String motorId);
    
    /**
     * 根据测量时间范围查询退化记录
     */
    List<AmArchivesDegradation> findByMeasurementTimeBetween(Date startTime, Date endTime);
    
    /**
     * 查询指定电机在给定时间范围内的退化记录
     */
    @Query("SELECT d FROM AmArchivesDegradation d WHERE d.motorId.motorId = :motorId AND d.measurementTime BETWEEN :startTime AND :endTime")
    List<AmArchivesDegradation> findByMotorIdAndTimeRange(
            @Param("motorId") String motorId,
            @Param("startTime") Date startTime,
            @Param("endTime") Date endTime
    );
    
    /**
     * 查询特定ID的退化记录，同时加载电机基本信息
     * 避免懒加载异常
     */
    @Query("SELECT d FROM AmArchivesDegradation d JOIN FETCH d.motorId WHERE d.degradationId = :degradationId")
    Optional<AmArchivesDegradation> findByIdWithMotorBase(@Param("degradationId") Integer degradationId);
    
    /**
     * 分页查询所有退化记录，同时加载电机基本信息
     * 避免懒加载异常
     */
    @Query(value = "SELECT DISTINCT d FROM AmArchivesDegradation d " +
           "LEFT JOIN FETCH d.motorId m " +
           "ORDER BY d.measurementTime DESC",
           countQuery = "SELECT COUNT(DISTINCT d) FROM AmArchivesDegradation d")
    Page<AmArchivesDegradation> findAllWithMotorBase(Pageable pageable);
    
    /**
     * 直接查询特定退化记录的电机ID字符串
     * 用于处理懒加载代理对象的问题
     */
    @Query("SELECT m.motorId FROM AmArchivesDegradation d JOIN d.motorId m WHERE d.degradationId = :degradationId")
    String findMotorIdByDegradationId(@Param("degradationId") Integer degradationId);

    @Query("SELECT new org.example.managere.dto.feibiao.AmArchivesDegradationDto(" +
           "d.degradationId, m.motorId, d.measurementTime, d.efficiencyDegradation, d.powerDegradation, d.remainingLifePrediction, m.motorType, m.manufacturer) " +
           "FROM AmArchivesDegradation d LEFT JOIN d.motorId m WHERE (:motorId IS NULL OR m.motorId = :motorId)")
    Page<AmArchivesDegradationDto> findAllDtoByMotorId(@Param("motorId") String motorId, Pageable pageable);
} 